document.addEventListener('DOMContentLoaded', async () => {
  const proxySwitch = document.getElementById('proxySwitch');
  const statusElement = document.getElementById('status');

  // 从存储中加载代理状态和配置
  const { proxyEnabled, proxyConfig } = await chrome.storage.local.get(['proxyEnabled', 'proxyConfig']);
  
  // 设置开关初始状态
  proxySwitch.checked = proxyEnabled || false;
  updateStatus(proxyEnabled, proxyConfig);

  // 监听开关变化
  proxySwitch.addEventListener('change', async (e) => {
    const enabled = e.target.checked;
    
    // 通知background script更新代理设置
    try {
      await chrome.runtime.sendMessage({ 
        type: 'updateProxyState', 
        enabled: enabled 
      });
      // 只有在代理设置成功应用后才更新UI
      const { proxyConfig } = await chrome.storage.local.get('proxyConfig');
      updateStatus(enabled, proxyConfig);
    } catch (error) {
      console.error('Failed to update proxy state:', error);
      // 如果更新失败，恢复开关状态
      proxySwitch.checked = !enabled;
      updateStatus(!enabled, proxyConfig);
    }
  });

  // 更新状态显示
  function updateStatus(enabled, config) {
    if (enabled && config) {
      statusElement.textContent = `当前状态: 已连接 - ${config.host}:${config.port}`;
      statusElement.style.backgroundColor = '#E8F5E9';
    } else {
      statusElement.textContent = '当前状态: 未连接';
      statusElement.style.backgroundColor = '#f5f5f5';
    }
  }

  // 监听来自background的状态更新
  chrome.runtime.onMessage.addListener((message) => {
    if (message.type === 'proxyStatusUpdate') {
      updateStatus(message.enabled, message.config);
    }
  });
});